"""
认证相关依赖和工具
"""


from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession

from src.crud import family_crud
from src.database import get_db
from src.models.family_model import FamilyMember, FamilyRole
from src.security import verify_token

# HTTP Bearer token 认证
security = HTTPBearer()


async def get_current_family_member(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: AsyncSession = Depends(get_db),
) -> FamilyMember:
    """
    获取当前认证的家庭成员
    """
    token = credentials.credentials
    member_id = verify_token(token)

    if member_id is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证凭据",
            headers={"WWW-Authenticate": "Bearer"},
        )

    family_member = await family_crud.get_family_member_by_id(db, member_id=member_id)
    if family_member is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return family_member


async def get_current_active_family_member(
    current_family_member: FamilyMember = Depends(get_current_family_member),
) -> FamilyMember:
    """
    获取当前活跃的家庭成员
    """
    if not bool(current_family_member.is_active):
        raise HTTPException(status_code=400, detail="用户已被禁用")
    return current_family_member


def require_role(allowed_roles: list[FamilyRole]):
    """
    角色验证装饰器
    """

    def role_checker(
        current_user: FamilyMember = Depends(get_current_active_family_member),
    ):
        # 获取用户的角色
        if hasattr(current_user.role, "value"):
            user_role = FamilyRole(current_user.role.value)
        else:
            user_role = current_user.role

        if user_role not in allowed_roles:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"权限不足, 需要以下角色之一: {', '.join([role.value for role in allowed_roles])}",
            )
        return current_user

    return role_checker


# 便捷的角色检查依赖
require_admin = require_role([FamilyRole.ADMIN])
require_member = require_role([FamilyRole.ADMIN, FamilyRole.MEMBER])
require_child = require_role([FamilyRole.ADMIN, FamilyRole.MEMBER, FamilyRole.CHILD])
require_guest = require_role(
    [FamilyRole.ADMIN, FamilyRole.MEMBER, FamilyRole.CHILD, FamilyRole.GUEST]
)
